import calendar
from django.contrib.admin.models import LogEntry
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions
from .models import *
from .serializers import *
import random
import json
import datetime
import requests
from django.core.cache import cache
import logging

from django.shortcuts import render
from django.http import JsonResponse

from ctbloge.apps.cms.models import Article
from ctbloge.apps.comments.models import Comment


class SiteInfoViewSet(viewsets.ModelViewSet):
    queryset = SiteInfo.objects.all().order_by('id')
    serializer_class = SiteInfoSerializer
    permission_classes = [permissions.AllowAny]

    @action(methods=['get'], detail=False)
    def about(self, request):
        site_info = SiteInfo.objects.first()
        serializer = AboutSiteInfoSerializer(site_info)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def blogfooter(self, request):
        site_info = SiteInfo.objects.first()
        serializer = BlogfooterInfoSerializer(site_info)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def blogheader(self, request):
        site_info = SiteInfo.objects.first()
        serializer = BlogHeaderInfoSerializer(site_info)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def get_reward_info(self, request):
        site_info = SiteInfo.objects.first()
        serializer = ArticleDetailInfoSerializer(site_info)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def get_blog_background(self, request):
        site_info = SiteInfo.objects.first()
        serializer = BackgroundImageSerializer(site_info)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def get_auth_info(self, request):  # 获取第三方登录信息
        site_info = SiteInfo.objects.first()
        serializer = SiteAuthSerializer(site_info)
        return Response(serializer.data)


class FriendLinkViewSet(viewsets.ModelViewSet):
    queryset = FriendLink.objects.all().order_by('rank')
    serializer_class = FriendLinkSerializer
    permission_classes = [permissions.AllowAny]

    @action(methods=['get'], detail=False)
    def random(self, request):  # 随机获取15条未失联的友情链接
        links = FriendLink.objects.filter(is_lost=False).order_by('?')[:15]
        serializer = FriendLinkSerializer(links, many=True)
        return Response(serializer.data)


class CarouselViewSet(viewsets.ModelViewSet):
    queryset = Carousel.objects.filter(is_show=True).order_by('rank')
    serializer_class = CarouselSerializer
    permission_classes = [permissions.AllowAny]

    # 获取随机的3张轮播图
    @action(methods=['get'], detail=False)
    def random(self, request):
        carousels = Carousel.objects.filter(is_show=True).order_by('?')[:3]
        # 对随机选择的结果，根据 id 进行二次排序
        carousels = sorted(carousels, key=lambda x: x.id)
        serializer = CarouselSerializer(carousels, many=True)
        return Response(serializer.data)


class AnnouncementViewSet(viewsets.ModelViewSet):
    queryset = Announcement.objects.all().order_by('rank')
    serializer_class = AnnouncementSerializer
    permission_classes = [permissions.AllowAny]


class MenuViewSet(viewsets.ModelViewSet):
    queryset = Menu.objects.all().order_by('rank')
    serializer_class = MenuSerializer
    permission_classes = [permissions.AllowAny]

    def get_queryset(self):
        queryset = Menu.objects.filter(is_show=True)
        parent_id = self.request.query_params.get('parent_id')
        if parent_id:
            queryset = queryset.filter(parent_id=parent_id)
        return queryset

    # 菜单树形结构接口，返回所有一级菜单以及其子菜单
    @action(methods=['get'], detail=False)
    def tree(self, request):
        menus = Menu.objects.filter(parent=None, is_show=True)
        parent_menus = []
        for menu in menus:
            children = menu.children.filter(is_show=True)
            parent_menu = {
                'id': menu.id,
                'name': menu.name,
                'url': menu.url,
                'icon': menu.icon,
                'children': MenuSerializer(children, many=True).data
            }
            parent_menus.append(parent_menu)
        return Response(parent_menus)


logger = logging.getLogger(__name__)


def get_daily_sentence(request):
    today = datetime.date.today().isoformat()
    cache_key = f'daily_sentence_{today}'
    cached = None

    # 带异常处理的缓存获取
    try:
        cached = cache.get(cache_key)
    except Exception as e:
        logger.error(f"Redis连接异常: {str(e)}")

    # 有效缓存直接返回
    if cached:
        return JsonResponse({'sentence': cached, 'cached': True})

    # 无缓存/缓存异常时的处理流程
    try:
        response = requests.get('https://v1.hitokoto.cn/', timeout=3)
        response.raise_for_status()
        data = response.json()
        sentence = data['hitokoto']

        # 带异常处理的缓存设置
        try:
            cache.set(cache_key, sentence, 86400)
        except Exception as e:
            logger.error(f"缓存写入失败: {str(e)}")

        return JsonResponse({
            'sentence': sentence,
            'cached': False,
            'cache_available': False  # 新增缓存状态标识
        })

    except requests.Timeout:
        logger.warning("第三方API请求超时")
        return JsonResponse({'error': '上游服务响应超时'}, status=503)
    except Exception as e:
        logger.error(f"数据获取异常: {str(e)}")
        return JsonResponse({'error': '服务暂时不可用'}, status=503)


def get_date_info(request):
    now = datetime.datetime.now()
    weekdays = ['日', '一', '二', '三', '四', '五', '六']
    date_str = f"{now.year}年{now.month}月{now.day}日 星期{weekdays[now.weekday()]}"
    return JsonResponse({'date_info': date_str})

def calculate_monthly_growth(model, date_field):
    growth_list = list()
    now = datetime.datetime.now()
    for i in range(1, 13):
        start_date = datetime.date(now.year, i, 1)
        end_date = datetime.date(now.year, i, calendar.monthrange(now.year, i)[1])
        growth_list.append(model.objects.filter(**{f"{date_field}__range": (start_date, end_date)}).count())
    return growth_list
def dashboard(request):
    now = datetime.datetime.now()
    users_count = UserProfile.objects.count()  # 获取用户数量
    # 获取活跃用户数量
    active_users = UserProfile.objects.filter(last_login__gte=now - datetime.timedelta(days=7))
    user_active_percentage = round(active_users.count() / users_count * 100, 2) if users_count > 0 else 0
    user_inactive_percentage = 100 - user_active_percentage
    articles_count = Article.objects.count()  # 获取文章数量
    comments_count = Comment.objects.count()  # 获取评论数量
    # 使用函数计算月度新增用户和新增文章的数量
    users_monthly_growth = calculate_monthly_growth(UserProfile, 'date_joined')
    articles_monthly_growth = calculate_monthly_growth(Article, 'modified_date')
    # 获取最近动作记录
    recent_actions = LogEntry.objects.all().order_by('-action_time')[:10]

    context = {
        'users_count': users_count,  # 获取用户数量
        'user_active_percentage': user_active_percentage,  # 活跃用户占比
        'user_inactive_percentage': user_inactive_percentage,  # 非活跃用户占比
        'articles_count': articles_count,  # 获取文章数量
        'comments_count': comments_count,  # 获取评论数量
        'recent_actions': recent_actions,  # 获取最近动作记录
        'users_monthly_growth': users_monthly_growth,  # 月度新增用户列表
        'articles_monthly_growth': articles_monthly_growth,  # 月度新增文章列表
    }
    return render(request, 'admin/dashboard.html', context)
